import json

import pulsar
import requests

from model.pulsar_tenant import PulsarTenant
from ui.notification_manager import NotificationManager


class TenantManageService:
    """
    租户管理
    """

    def __init__(self, pulsar_cluster, parent=None):
        self.cluster = pulsar_cluster
        self.client = pulsar.Client(self.cluster.pulsar_addr)
        self.notification_manager = NotificationManager(parent)

    def get_tenant_list(self):
        """
        获取集群树节点
        :return:
        """
        url = self.cluster.admin_addr + "/admin/v2/tenants"
        response = requests.get(url)
        if response.status_code != 200:
            return Exception(str(response.status_code))

        tenants = []
        for name in json.loads(response.content):
            tenants.append(PulsarTenant(name))

        return tenants

    def add_tenant(self, name, clusters):
        url = self.cluster.admin_addr + "/admin/v2/tenants/" + str(name)
        headers = {'Content-Type': 'application/json'}
        body = {
            "adminRoles": ["string"],
            "allowedClusters": clusters
        }
        response = requests.put(url, headers=headers, json=body)
        if response.status_code != 200:
            return Exception(str(response.status_code))
        print(response.content)

    def delete_tenant(self, name, force):
        url = self.cluster.admin_addr + "/admin/v2/tenants/" + str(name) + "?force=" + str(force)
        resp = requests.delete(url)
        if resp.status_code == 204:
            print(f"租户 {name} 删除成功")
            return True
        else:
            print(f"删除{name}失败:{resp.text}")
            return False

    def get_clusters(self):
        getUrl = self.cluster.admin_addr + "/admin/v2/clusters"
        clusres = requests.get(getUrl)

        clus = []
        for name in json.loads(clusres.content):
            clus.append(name)

        return clus

    def get_name_space(self, tenant):
        try:
            getUrl = self.cluster.admin_addr + "/admin/v2/namespaces/" + str(tenant)
            resp = requests.get(getUrl)
            list = []
            for name in json.loads(resp.content):
                list.append(name)
            return list
        except Exception as e:
            self.notification_manager.show_error("Connection Error", str(e))
            return []

    def get_topics(self, nameSpace):
        try:
            #  https://pulsar.apache.org/admin/v2/persistent/{tenant}/{namespace}
            getUrl = self.cluster.admin_addr + "/admin/v2/persistent/" + str(nameSpace)
            resp = requests.get(getUrl)
            list = []
            for name in json.loads(resp.content):
                list.append(name)
            getUrl = self.cluster.admin_addr + "/admin/v2/non-persistent/" + str(nameSpace)
            resp = requests.get(getUrl)
            for name in json.loads(resp.content):
                list.append(name)
            list.sort()
            return list
        except Exception as e:
            self.notification_manager.show_error("Connection Error", str(e))
            return []

    def get_topic_status(self, topicName):
        try:
            #  https://pulsar.apache.org/admin/v2/non-persistent/{tenant}/{namespace}/{topic}/internalStats
            if topicName.startswith("persistent"):
                getUrl = self.cluster.admin_addr + "/admin/v2/persistent/" + str(topicName).replace('persistent://',
                                                                                                    '') + "/internalStats"
            else:
                getUrl = self.cluster.admin_addr + "/admin/v2/non-persistent/" + str(topicName).replace(
                    'non-persistent://', '') + "/internalStats"
            resp = requests.get(getUrl)
            return resp.content.decode('utf-8')
        except Exception as e:
            self.notification_manager.show_error("Connection Error", str(e))
            return []
